package com.fxcalibre.onlineServices.imdb.parser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.fxcalibre.onlineServices.beans.TitleResult;

public class ImdbTitleSearchParser
{
	private final static Logger log = Logger.getLogger(ImdbTitleSearchParser.class.getName());

	public static List<TitleResult> parse(String htmInput)
	{
		List<TitleResult> result = new ArrayList<TitleResult>();
		Document doc = Jsoup.parse(htmInput);
		Elements content = doc.select("table.results tr.detailed");

		for (Iterator<Element> iterator = content.iterator(); iterator.hasNext();)
		{
			log.fine("-->");
			TitleResult titleResult = new TitleResult();
			Element element = (Element) iterator.next();
			titleResult.setImgUrl(getFirstFound(element, "td.image img", "src"));
			titleResult.setName(getFirstFound(element, "td.title a", null));
			titleResult.setId(getFirstFound(element, "td.title a", "href"));
			titleResult.setCredits(getFirstFound(element, "span.credit", null));
			titleResult.setDescription(getFirstFound(element, "span.outline", null));

			result.add(titleResult);
			log.fine(titleResult.toString());

			log.fine("<--");
		}

		return result;
	}
	
	private static String getFirstFound(Element element, String select, String attr)
	{
		Elements elems = element.select(select);
		if (elems.size() > 0)
		{
			if (attr != null)
			{
				return elems.get(0).attr(attr);
			} else
			{
				return elems.get(0).text();
			}
		}

		return null;
	}
}
